package com.aaa.moneymanage.controller.api;

import com.aaa.entity.*;
import com.aaa.moneymanage.services.CareHistoryServices;
import com.aaa.moneymanage.services.MoneyinServices;
import com.aaa.moneymanage.services.MoneyoutServices;
import com.aaa.moneymanage.utils.GetString;
import com.aaa.moneymanage.utils.HttpClient;
import com.aaa.moneymanage.vo.PostObjVo;
import com.aaa.vo.Result;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author ：XiaoxXuan
 * @date ：Created in 2023/3/28 10:31
 * @description：localhost:8085/pay/alipay
 * @modified By：
 */
@RestController
@RequestMapping("/charge/api/ali")
public class AlipayController {

    @Resource
    private GetString getString;

    @Resource
    private CareHistoryServices careHistoryServices;

    @Resource
    private MoneyinServices moneyinServices;

    @Resource
    private MoneyoutServices moneyoutServices;

    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;


    //生成二维码
    @GetMapping("carateNative")
    public Result<List<CareOrderItem>> carateNative(String patientName){

        //获取当前用户的名字
        String username = getString.getUsername();

        //生成orderId
        String orderId = "ODC";
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            orderId += String.valueOf(random.nextInt(10));
        }
        try {
            //设置请求的参数--格式为xml
            Map<String, String> params = new HashMap<>();//请求参数
            params.put("appid", appId);//公众号ID
            params.put("mch_id", mchId);//商品号id
            params.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            params.put("body", patientName);//标题
            params.put("out_trade_no", orderId);//订单号
            //支付金额0.01 未来换成真是的金额
            params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
            params.put("spbill_create_ip", "127.0.0.1");//未来写成项目部署的ip
            params.put("notify_url", "http:localhost:8090/charge/api/hisOrderCharge");
            params.put("trade_type", "NATIVE");//支付方式使用PC
            //创建httpClient对象 作用远程调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //支持https协议
            client.setHttps(true);
            //设置请求参数
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            //发送请求
            client.post();
            //获取请求的相应结果
            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("result_code").equals("SUCCESS")) {
                Map<String, Object> result = new HashMap<>();
                result.put("codeUrl", map.get("code_url"));
                result.put("orderId", orderId);
                return new Result(200, "生成二维码成功", result);

            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return new Result<>(200, "订单失效", null);

    }


    //确定订单完成微信收费
    @PostMapping("verify")
    @Transactional
    public Result updateTheStatus(@RequestBody PostObjVo postObjVo ){

        //从前端传的集合中获取数据
        String regId = postObjVo.getOrderChargeDto().getRegId();
        String orderId = postObjVo.getOrderChargeDto().getOrderId();
        BigDecimal orderAmount = postObjVo.getOrderChargeDto().getOrderAmount();
        String[] itemIds = postObjVo.getOrderChargeItemDtoList();

        //获取当前用户的名字
        String username = getString.getUsername();

        //修改状态 未支付=》已支付
        for (String itemId : itemIds) {
            careHistoryServices.updateTheStatus(itemId,"1");
        }

        //获取localdatatime类型的当前时间
        LocalDateTime now = LocalDateTime.now();

        CareHistory careHistory = careHistoryServices.getCareHistoryByRegId(regId);

        List<CareOrderItem> careOrderItems = careHistoryServices.getCareOrderItemByRegId(regId);

        HashMap<String, List<CareOrderItem>> stringListHashMap = new HashMap<>();
        for (String itemId : itemIds) {
            List<CareOrderItem> collect = careOrderItems.stream().filter(item -> item.getItemId().equals(itemId)).collect(Collectors.toList());
            stringListHashMap.put(itemId,collect);
        }

        OrderCharge orderCharge = new OrderCharge();
        orderCharge.setOrderId(orderId);
        orderCharge.setOrderAmount(orderAmount);
        orderCharge.setChId(careHistory.getChId());
        orderCharge.setRegId(regId);
        orderCharge.setPatientName(careHistory.getPatientName());
        orderCharge.setOrderStatus("1");
        orderCharge.setPayPlatformId("415411");
        orderCharge.setPayTime(now);
        orderCharge.setPayType("1");
        orderCharge.setCreateTime(now);
        orderCharge.setCreateBy(username);

        moneyinServices.insertOrderCharge(orderCharge);


        for (String s : stringListHashMap.keySet()) {

            CareOrderItem careOrderItem = stringListHashMap.get(s).get(0);
            OrderChargeItem orderChargeItem = new OrderChargeItem();
            orderChargeItem.setItemId(s);
            orderChargeItem.setCoId(careOrderItem.getCoId());
            orderChargeItem.setItemName(careOrderItem.getItemName());
            orderChargeItem.setItemPrice(careOrderItem.getPrice());
            orderChargeItem.setItemNum(careOrderItem.getNum().intValue());
            orderChargeItem.setItemAmount(careOrderItem.getAmount());
            orderChargeItem.setOrderId(orderId);
            orderChargeItem.setItemType(careOrderItem.getItemType());
            orderChargeItem.setStatus(careOrderItem.getStatus());

            moneyinServices.insertOrderChargeItem(orderChargeItem);
        }

        return new Result(200,"锅巴喷火！");

    }

    //微信退费
    @PostMapping("backfee")
    @Transactional
    public Result backfee(@RequestBody PostObjVo postObjVo ){

        //生成backId
        String backId= "ODB";
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            backId += String.valueOf(random.nextInt(10));
        }

        //从前端传的集合中获取数据
        String regId = postObjVo.getOrderChargeDto().getRegId();
        BigDecimal orderAmount = postObjVo.getOrderChargeDto().getOrderAmount();
        String[] itemIds = postObjVo.getOrderChargeItemDtoList();

        //获取当前用户的名字
        String username = getString.getUsername();

        //修改药方表状态
        for (String itemId : itemIds) {
            careHistoryServices.updateTheStatus(itemId,"2");
        }
        //修改收费查询表状态,顺便获取订单id
        String orderId = careHistoryServices.updateOrderChargeItemStatusByRegId(regId);

        LocalDateTime now = LocalDateTime.now();

        CareHistory careHistory = careHistoryServices.getCareHistoryByRegId(regId);

        List<CareOrderItem> careOrderItems = careHistoryServices.getCareOrderItemByRegId(regId);

        HashMap<String, List<CareOrderItem>> stringListHashMap = new HashMap<>();
        for (String itemId : itemIds) {
            List<CareOrderItem> collect = careOrderItems.stream().filter(item -> item.getItemId().equals(itemId)).collect(Collectors.toList());
            stringListHashMap.put(itemId,collect);
        }

        OrderBackfee orderBackfee = new OrderBackfee();
        orderBackfee.setBackId(backId);
        orderBackfee.setBackAmount(orderAmount);
        orderBackfee.setChId(careHistory.getChId());
        orderBackfee.setRegId(regId);
        orderBackfee.setPatientName(careHistory.getPatientName());
        orderBackfee.setBackStatus("1");
        orderBackfee.setBackType("1");
        orderBackfee.setOrderId(orderId);
        orderBackfee.setBackPlatformId("414");
        orderBackfee.setBackTime(now);
        orderBackfee.setCreateTime(now);
        orderBackfee.setCreateBy(username);

        moneyoutServices.insertOrderBackfee(orderBackfee);

        for (String s : stringListHashMap.keySet()) {

            CareOrderItem careOrderItem = stringListHashMap.get(s).get(0);
            OrderBackfeeItem orderBackfeeItem = new OrderBackfeeItem();
            orderBackfeeItem.setItemId(s);
            orderBackfeeItem.setCoId(careOrderItem.getCoId());
            orderBackfeeItem.setItemName(careOrderItem.getItemName());
            orderBackfeeItem.setItemPrice(careOrderItem.getPrice());
            orderBackfeeItem.setItemNum(careOrderItem.getNum().intValue());
            orderBackfeeItem.setItemAmount(orderAmount);
            orderBackfeeItem.setBackId(backId);
            orderBackfeeItem.setItemType(careOrderItem.getItemType());
            orderBackfeeItem.setStatus(careOrderItem.getStatus());

            moneyoutServices.insertOrderBackfeeItem(orderBackfeeItem);

        }

        return new Result(200,"香菱");

    }


}